import Vue from 'vue'
import asyncRouterMap from '@/sysrouter'
import { login, logout, getUserRoutes } from '@/api/login'
import { getToken, setToken, removeToken,
  getUserCode, setUserCode, removeUserCode,
  getUserInfo, setUserInfo, removeUserInfo,
  getMainRoutes, setMainRoutes, removeMainRoutes,
  getRoleBtns, setRoleBtns, removeRoleBtns,
  makeRoutesTool,
  makeRoleBtns
} from '@/utils/auth'

const user = {
  state: {
    token: getToken(),
    userInfo: getUserInfo(),
    // 获取用户code
    userCode: getUserCode(),
    baseroutes: [], // 权限路由
    loadRoutes: false, // 是否添加过动态路由
    mainroutes: getMainRoutes(), // 从后台获取的用户可访问的路由信息
    sideroutes: [], // 侧边栏数据
    changePwdFlag: false,
    roleBtns: makeRoleBtns(getRoleBtns()) // 权限按钮
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_USERINfO: (state, userInfo) => {
      state.userInfo = userInfo
    },
    // 设置usercode
    SET_USERCODE: (state, userCode) => {
      state.userCode = userCode
    },
    // 存储侧边栏路由信息和路由基本信息
    SET_BASEROUTES: (state, data) => {
      if (!data) {
        state.baseroutes = []
        state.sideroutes = []
        return
      }
      state.baseroutes = data
      const newrouter = Vue.prototype.constantRouterMap.concat(data)
      state.sideroutes = newrouter
    },
    // 存储从后台获取的路由信息
    SET_MAINROUTES: (state, data) => {
      state.mainroutes = data
    },
    // 设置是否加载过动态路由
    SET_LOADROUTES(state, data) {
      state.loadRoutes = data
    },
    // 设置用户权限按钮
    SET_ROLEBTNS(state, data) {
      if (!data) {
        state.roleBtns = {}
        return
      }
      state.roleBtns = data
    }
  },

  actions: {
    // 登录 获取用户信息
    Login({ commit, dispatch }, userInfo) {
      const username = userInfo.userCode.trim()
      return new Promise((resolve, reject) => {
        login(username, userInfo.userPassword).then(response => {
          const data = response
          setToken(data.token)
          commit('SET_TOKEN', data.token)
          setUserCode(data.user.username)
          commit('SET_USERCODE', data.user.username)
          setUserInfo(data.user)
          commit('SET_USERINfO', data.user)
          setRoleBtns(data.user.roles)
          commit('SET_ROLEBTNS', makeRoleBtns(data.user.roles))
          Promise.all([dispatch('getUserRoutes')]).then(() => {
            resolve()
          }).catch(() => {
            reject()
          })
        }).catch(error => {
          console.log(error)
          reject(error)
        })
      })
    },
    // 获取用户可访问的路由信息
    getUserRoutes({ commit }) {
      return new Promise((resolve, reject) => {
        getUserRoutes().then(res => {
          if (!res) throw new Error('没有获取到路由信息')
          setMainRoutes(res)
          commit('SET_MAINROUTES', res)
          resolve(res)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 合成路由
    makeRoutes({ commit }) {
      return new Promise((resolve, reject) => {
        try {
          const baseroutes = makeRoutesTool(getMainRoutes(), asyncRouterMap)
          commit('SET_BASEROUTES', baseroutes)
          resolve(baseroutes)
        } catch (err) {
          console.log(err)
          reject(err)
        }
      })
    },
    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout().then(() => {
          removeToken()
          commit('SET_TOKEN', '')
          removeUserInfo()
          commit('SET_USERINfO', '')
          removeUserCode()
          commit('SET_USERCODE', '')
          removeMainRoutes()
          commit('SET_MAINROUTES', '')
          commit('SET_LOADROUTES', false)
          removeRoleBtns()
          commit('SET_ROLEBTNS', '')
          // commit('SET_BASEROUTES', '')
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        removeToken()
        commit('SET_TOKEN', '')
        removeUserInfo()
        commit('SET_USERINfO', '')
        removeUserCode()
        commit('SET_USERCODE', '')
        removeMainRoutes()
        commit('SET_MAINROUTES', '')
        commit('SET_LOADROUTES', false)
        removeRoleBtns()
        commit('SET_ROLEBTNS', '')
        // commit('SET_BASEROUTES', '')
        resolve()
      })
    }
  }
}

export default user

